#!/bin/bash

# Copyright (c) 2025 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# ----------------------------------------- 环境变量 -----------------------------------------
NODE_HOME=
COMPONT_NAME=
# 获取脚本的绝对路径（支持符号链接）
script_path=$(readlink -f "${BASH_SOURCE}" 2>/dev/null || readlink "${BASH_SOURCE}" 2>/dev/null || echo "${BASH_SOURCE}")
script_dir=$(dirname "$script_path")
echo "script_dir=$script_dir"

# 设置node路径
NODE_HOME=$script_dir/command-line-tools/tool/node
export NODE_HOME=${NODE_HOME}
echo -e "\nNODE_HOME = $NODE_HOME"
export PATH=$NODE_HOME:$PATH
echo -e "\nPATH = $PATH"
export PATH=$NODE_HOME/bin:$PATH
echo -e "\nPATH = $PATH"

# ----------------------------------------- 函数 -----------------------------------------
function check_git_tools() {
    echo -e "\n---------------------------------check_git_tools start---------------------------------"

    echo -e "\nldd --version | grep ldd"
    ldd --version | grep ldd

    # 检查是否安装git
    echo -e '\ngit --version:'
    git --version
    if [ $? -ne 0 ]
    then
        # 安装git
        echo -e '\napt install git -y:'
        apt install git -y
        echo ''
    fi

    # 检查是否安装git大文件处理扩展
    echo -e '\ngit lfs version:'
    git lfs version
    if [ $? -ne 0 ]
    then
        # 安装大文件扩展
        echo -e '\napt install git-lfs:'
        apt install git-lfs
        echo ''
    fi

    echo -e "---------------------------------check_git_tools finished---------------------------------\n"
    return 0
}

function prepare_commandlinetools() {
    echo -e "\n---------------------------------prepare_commandlinetools start---------------------------------"

    # 检查command-line-tools目录是否存在
    if [ -d "$script_dir/command-line-tools" ];then
        echo "command-line-tools exists, do not download again."
    else
        # TODO：使用镜像网站下载command-line-tools，当前为从gitcode仓下载
        # if [ ! -f "command-line-tools.zip" ];then
        #     echo "start download command-line-tools.zip"
        #     curl -o "commandline-tools-linux.zip" https://repo.huaweicloud.com/harmonyos/ohpm/5.0.5/commandline-tools-linux-x64-5.0.5.310.zip

        #     # 判断是否下载成功
        #     if [ $? != 0 ];then
        #         echo "download commandline-tools-linux.zip failed."
        #         rm -rf commandline-tools-linux.zip
        #         return 1
        #     fi
        # fi
        # 开始解压zip包
        # echo 'unzip -oqq "./commandline-tools-linux.zip"：'
        # unzip -oqq "./commandline-tools-linux.zip"
        # echo "finish unzip command-line-tools.zip"

        # commandline-tools-linux.zip 文件为LFS指针需重新下载
        echo -e "\nls -l ./:"
        ls -l ./

        echo -e "\npwd:"
        pwd

        # 初始化git lfs
        echo -e '\ngit lfs install:'
        git lfs install
        # 下载大文件
        echo -e "\ngit lfs pull --include=\"commandline-tools-linux.zip\":"
        git lfs pull --include="commandline-tools-linux.zip" > /dev/null

        if [ $? == 0 ]
        then
            echo "commandline-tools-linux.zip download success"
        else 
            echo "commandline-tools-linux.zip download fail"
            # exit 1
        fi

        # zip包替换需使用git lfs扩展提交
        # 解压zip包
        echo 'unzip -oqq "./commandline-tools-linux.zip":'
        unzip -oqq "./commandline-tools-linux.zip"
        echo "finish unzip command-line-tools.zip"

        # 准备node环境
        chmod 777 $NODE_HOME/bin/*

        echo -e "\n$NODE_HOME/bin/npm config set strict-ssl false:"
        $NODE_HOME/bin/npm config set strict-ssl false

        echo -e "\n$NODE_HOME/bin/npm config set registry=https://repo.huaweicloud.com/repository/npm/:"
        $NODE_HOME/bin/npm config set registry=https://repo.huaweicloud.com/repository/npm/
        
        echo -e "\n$NODE_HOME/bin/npm config set @ohos:registry=https://repo.harmonyos.com/npm/:"
        $NODE_HOME/bin/npm config set @ohos:registry=https://repo.harmonyos.com/npm/
    fi
    echo -e "---------------------------------prepare_commandlinetools finish---------------------------------\n"

    return 0
}

function get_warehouse_name() {
    echo -e "\n---------------------------------get_warehouse_name start---------------------------------"

    local res=0
    local pr_name=$1

    # 示例：pr_name=https://gitcode.com/HarmonyOS_Codelabs/NativeTemplate/pull/1
    if [[ $pr_name == *HarmonyOS_Codelabs* ]]
    then
        pr_name=${pr_name#*HarmonyOS_Codelabs/}
    else
        pr_name=${pr_name#*HarmonyOS_Samples/}
        HAP_FILE_DIR=$ROOT_DIR/out/samples/packages
        export HAP_FILE_DIR=${HAP_FILE_DIR}
        mkdir -p $HAP_FILE_DIR
    fi
    # 示例：pr_name=NativeTemplate/pull/1

    local pull_request=
    if [[ $pr_name == *pull* ]]
    then
        pull_request="pull"
    else 
        pull_request="merge_requests"
    fi

    # 示例：pr_name=NativeTemplate/pull/1
    COMPONT_NAME=${pr_name%/${pull_request}*}
    # 示例：COMPONT_NAME=NativeTemplate

    # 输出代码仓名
    echo "COMPONT_NAME=$COMPONT_NAME"

    export COMPONT_NAME=$COMPONT_NAME

    echo -e "\n---------------------------------get_warehouse_name finish---------------------------------\n"
    return $res
}

function prepare() {
    echo -e "\n---------------------------------prepare start---------------------------------"

    echo "PR_URL=$1"

    # 检查git环境
    check_git_tools

    # 准备ohpm/hvigor/sdk等环境
    prepare_commandlinetools

    # 初始化ohpm
    ohpm_init

    # 获取代码仓名
    get_warehouse_name $1

    # 检查仓库是否为多工程
    check_multi_project $1

    echo -e "---------------------------------prepare finish---------------------------------\n"
    return 0
}


function download_diff() {
    echo -e "\n---------------------------------download_diff start---------------------------------"
    # 示例：diff_url=https://gitcode.com/HarmonyOS_Codelabs/NativeTemplate/pull/1
    local diff_url=$1
    # 示例：pr_num=1
    local pr_num=${diff_url##*/}

    # 示例：tmp=HarmonyOS_Codelabs/NativeTemplate/pull/1
    local tmp=${diff_url##*com/}
    # 示例：organization=HarmonyOS_Codelabs
    # 区分HarmonyOS_Codelabs及HarmonyOS_Samples
    local organization=${tmp%%/*}
    
    local url="https://api.gitcode.com/api/v5/repos/$organization/$COMPONT_NAME/pulls/$pr_num/diff"
    echo "url = $url"

    # gitcode个人令牌，为保安全个人令牌需配置为只读权限，过期需更新
    local token="Az_CgcqzwxP6EPkqZPi_fnxR"
    curl --location \
    $url \
    --header "PRIVATE-TOKEN: $token" \
    -o $pr_num.diff

    echo -e "---------------------------------download_diff finish---------------------------------\n"
    return 0
}


function check_multi_project() {
    echo -e "\n---------------------------------check_multi_project start---------------------------------"
    # 仓库下是包含oh-package.json5，则为单工程
    if [ -f "$ROOT_DIR/$COMPONT_NAME/oh-package.json5" ]
    then
        echo "project is single project"
        echo -e "---------------------------------check_multi_project finish---------------------------------\n"
        return 0
    fi

    local diff_url=$1
    local pr_num=${diff_url##*/}
    local diff_name=$pr_num.diff
    local retval=1
    local compont_name=
    if [ -f $diff_name]
    then
        rm $diff_name
    fi
    
    # 下载diff文件
    download_diff $1

    PROJECT_NAMES=
    local diff_str=`cat $diff_name | grep "diff --git"`
    if [ -z "$diff_str" ]
    then
        echo "download diff failed!"
        echo -e "---------------------------------download_diff finish---------------------------------\n"
        exit 1
    fi

    # 示例：diff = "diff --git a/AppDataSecurity/entry/src/main/ets/pages/Index.ets b/AppDataSecurity/entry/src/main/ets/pages/Index.ets"
    # 示例：diff = "diff --git a/AppPrivacyProtection/entry/src/main/ets/pages/Index.ets b/AppPrivacyProtection/entry/src/main/ets/pages/Index.ets"
    for diff in $diff_str
    do
        local tmp=`echo $diff | grep "/"`
        if [ ! -z "$tmp" ]
        then
            # 示例：tmp=a/AppDataSecurity/entry/src/main/ets/pages/Index.ets
            # 示例：tmp=a/AppPrivacyProtection/entry/src/main/ets/pages/Index.ets
            tmp=${tmp#*/}
            # 示例：tmp=AppDataSecurity/entry/src/main/ets/pages/Index.ets
            # 示例：tmp=AppPrivacyProtection/entry/src/main/ets/pages/Index.ets
            
            local tmp_name=${tmp%%/*}
            # 示例：tmp_name=AppDataSecurity
            # 示例：tmp_name=AppPrivacyProtection
            
            if [[ $PROJECT_NAMES != *$tmp_name* ]]
            then
                PROJECT_NAMES="$PROJECT_NAMES $tmp_name"
                # 示例：PROJECT_NAMES="AppDataSecurity"
                # 示例：PROJECT_NAMES="AppDataSecurity AppPrivacyProtection"
            fi
        fi
    done

    echo "PROJECT_NAMES:$PROJECT_NAMES"
    echo -e "---------------------------------check_multi_project finish---------------------------------\n"
}

